package controllers;

import java.io.File;
import java.util.List;

import beans.PageBean;
import models.Photo;
import play.Play;
import play.libs.Codec;
import play.libs.Files;
import play.mvc.Controller;
import play.mvc.With;
import utils.Config;
import utils.ImageUtils;
import utils.MessageUtil;

/**
 *
 * @author Chen
 * 2014/9/23
 */
@With(value=CheckLogin.class)
public class Photos extends Controller{

    public static void index(int page){
        long total = Photo.count("type = ?",1);
        PageBean pageBean = PageBean.getInstance(page, total,5);
        List<Photo> photoList = Photo.find("type = ? order by createTime desc",1).fetch(pageBean.getCurPage(),pageBean.getPerPage());
        render(photoList,pageBean);
    }

    public static void addPhoto(){
        render();
    }

    public static void savePhoto(File image,int type){
        if(image != null){
            if(!ImageUtils.isVideoImageValid(image)){
                addPhoto();
            }
        }
        else{
            MessageUtil.generateInfoMsg("请选择图片");
               addPhoto();
        }

        String id = Codec.UUID();
        Files.copy(image, Play.getFile("file/imageFile/" + id+image.getName()));
        Photo.addPhoto(id + image.getName(), null);
        MessageUtil.generateInfoMsg("上传成功");
        addPhoto();
    }

    public static void delPhoto(String name,String id){
        File targetFile = new File(Config.imagePath, name);
        File originFile = new File(Config.originPath, name);
        Photo.delById(id);
        targetFile.delete();
        originFile.delete();
        Photos.index(0);
    }
}
